package com.adobe.apps.ascension.tips
{
	import mx.collections.ArrayCollection;
	import flash.filesystem.File;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	
	public class LocalTipManager implements ITipLoader
	{
		
		private var tips:ArrayCollection = new ArrayCollection();
		private const EXTENSION:String = "tip";
		private var _index:uint = 0;
		
		private var _hasNext:Boolean = false;;
		private var _hasPrevious:Boolean = false;		
		private var _count:uint = 0;
		
		public function LocalTipManager(tipDir:File)
		{
			if(!tipDir.exists || !tipDir.isDirectory)
			{
				return;
			}
			
			var tArray:Array = tipDir.listDirectory();
			
			var temp:Tip;
			for each(var t:File in tArray)
			{
				if(getExtension(t) != EXTENSION)
				{
					continue;
				}
				
				temp = new Tip();
				temp.content = readFileAsString(t);
				
				tips.addItem(temp);
			}
			updateIndex(0);
			count = tips.length;
		}
		
		[Bindable]
		public function get index():uint
		{
			return _index;
		}
		
		private function set index(v:uint):void
		{
			_index = v;
		}
		
		public function getCurrentTip():Tip
		{
			//check index for valid?
			return Tip(tips.getItemAt(index));
		}
		
		private function readFileAsString(f:File):String
		{
			var fs:FileStream = new FileStream();
				fs.open(f, FileMode.READ);
				var s:String = fs.readUTFBytes(fs.bytesAvailable);
				fs.close();
				
				return s;
		}
		
		private function getExtension(f:File):String
		{
			return f.name.substr(f.name.lastIndexOf(".") + 1);
		}		
		
		private function updateIndex(c:uint):void
		{
			index = c;
			
			hasNextTip = (index + 1 < tips.length);
			hasPreviousTip = (index != 0);
			
		}
		
		[Bindable]
		public function get hasNextTip():Boolean
		{
			return _hasNext;
		}
		
		private function set hasNextTip(b:Boolean):void
		{
			_hasNext = b;
		}
		
		[Bindable]
		public function get hasPreviousTip():Boolean
		{
			return _hasPrevious;
		}
		
		private function set hasPreviousTip(b:Boolean):void
		{
			_hasPrevious = b;
		}		
		
		[Bindable]
		public function get count():uint
		{
			return _count;
		}
		
		private function set count(v:uint):void
		{
			_count = v;
		}
		
		public function getNextTip():Tip
		{
			var tmp:uint = index + 1;
			
			if(tmp == tips.length)
			{
				updateIndex(0);
			}	
			else
			{
				updateIndex(tmp);
			}
			
			return Tip(tips.getItemAt(index));
		}
		
		public function getPreviousTip():Tip
		{
			var tmp:uint = index - 1;
			
			
			if(tmp < 0)
			{
				updateIndex(tips.length - 1);
			}
			else
			{
				updateIndex(tmp);
			}
			
			return Tip(tips.getItemAt(index));
		}
		
	}
}